# == Schema Information
#
# Table name: users
#
#  id         :integer          not null, primary key
#  mobile     :string(255)      not null              # 手机号
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class User < ActiveRecord::Base

  # 通用查询方法
  include Concerns::Query::Methods

  # 关联救援
  has_many :rescues


  #
  # 短信登录验证
  #
  # @param options [Hash]
  # @option options [String] :phone 手机号
  # @option options [String] :smsCode 验证码
  # @option options [String] :smsToken token
  #
  # @return [Array] 响应, 用户, token
  #
  def self.validate_login_with_sms_token(options)
    response_status = ResponseStatus.default
    user = nil
    token = nil

    begin
      raise RestError::MissParameterError if options[:phone].blank? || options[:smsCode].blank? || options[:smsToken].blank?
      phone, sms_code, usage = TsaoUtil.decode_sms_code(options[:smsToken])

      if options[:phone] == phone && options[:smsCode] == sms_code && usage == TsaoUtil::Usage::USER_SIGN_IN
        user = User.upsert_user_if_not_found(phone)
        token = TsaoUtil.sign_jwt_user_session(phone)
        response_status = ResponseStatus.default_success
      else
        response_status.message = '验证码不正确'
      end
    rescue Exception => ex
      Rails.logger.error(ex.message)
      response_status.message = ex.message
    end

    return response_status, user, token
  end

  # 如果此用户不存在则创建此用户并返回
  def self.upsert_user_if_not_found(phone = '')
    user = User.where({phone: phone}).first
    if user.blank?
      user = User.new
      user.phone = phone
      user.password = '123456'

      user.save!

      # options = {
      #     discount: 2,
      #     least_price: 3,
      #     activated_date: Time.now,
      #     expired_date: Time.now + 7.days,
      #     user: user
      # }
      #
      # #TODO 注册用户免费两张优惠券
      # Coupon.generate_coupon(options)
      # options[:discount] = 3
      # options[:least_price] = 5
      # Coupon.generate_coupon(options)

    end
    user
  end
end
